<html>
<body>
  <h1>Welcome to Cesanta Office Heater!</h1>

  <p>Temperature is <b id="temp"></b>&deg;C.</p>
  <p>Heater is <b id="status"></b>.</p>
  <form>
    <input type=submit value="Turn heater on" id="b1">
  </form>
  <hr>
  Device information: <pre id="fw"></pre>

  <script>
    function ajax(url, callback, data) {
      var httpRequest = new XMLHttpRequest();
      httpRequest.onreadystatechange = function() {
        if (httpRequest.readyState === 4) {
          if (httpRequest.status === 200 || httpRequest.status === 0) {
            try {
              var data = JSON.parse(httpRequest.responseText);
              if (callback) callback(data);
            } catch(e) {
              console.error('Unable to parse JSON', e);
            }
          }
        }
      };
      httpRequest.open('POST', url);
      httpRequest.send(JSON.stringify(data));
    }
    var el = function(id) { return document.getElementById(id); };
    var text = function(id, text) { el(id).innerHTML = text; };

    ajax('/rpc/Heater.GetState', function(json) {
      text('status', json.on ? 'on' : 'off');
      text('temp', json.temp);
      el('b1').setAttribute('value', 'Turn heater ' + (json.on ? 'off' : 'on'));
    });

    ajax('/rpc/Sys.GetInfo', function(json) {
      text('fw', JSON.stringify(json, null, '  '));
    });

    el('b1').onclick = function(ev) {
      var on = !!(el('b1').value || 'off').match(/on$/);
      ajax('/rpc/Heater.SetState', function() {
        location.reload();
      }, {state: on ? 1 : 0});
      return false;
    };

  </script>

</body>
</html>
